package org.boot.easyapi.file.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件存储配置类
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "easyapi.file.storage")
public class FileStorageConfig {

    /**
     * 文件存储路径
     */
    private String rootPath = defaultStoragePath();

    private long chunkSize;

    private boolean enableMd5;

    @PostConstruct
    private void init(){
        // 目录不存在时，自动创建
        createDir(this.rootPath);
    }


    private String defaultStoragePath(){
        String defaultStoragePath = "/home/easyapifiles/";
        if (System.getProperty("os.name").toLowerCase().contains("win")) {  //windows环境下
            defaultStoragePath = "C:/home/easyapifiles/";
        } else {  //linux/mac环境下
            defaultStoragePath = "/home/easyapifiles/";
        }
//        createDir(defaultStoragePath);
        return defaultStoragePath;
    }


//    public FileStorageConfig(){
//        createDir(this.rootPath);
//    }

    private void createDir(String defaultStoragePath) {
        Path path = Paths.get(defaultStoragePath);
        if (Files.notExists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                throw new RuntimeException("自动创建目录失败: " + defaultStoragePath, e);
            }
        }
    }
}